package com.kly.user.chatterService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.kly.user.db.dao.*;
import com.kly.user.db.dbo.UserMessageReporDBO;
import com.kly.user.db.dbo.UserMessageReportDBO;
import com.kly.user.db.entity.*;
import com.kly.user.dto.UserInfoDto;
import com.kly.user.dto.chatter.response.AlbumsResponseDto;
import com.kly.user.dto.chatter.response.ChatterDashboardDto;
import com.kly.user.dto.chatter.response.UserChatterDto;
import com.kly.user.dto.chatter.response.UserChatterModeDto;
import com.kly.user.mapper.UserAlbumsContentMapper;
import com.kly.user.mapper.UserMapper;
import com.kly.user.utils.ImagePrefixUtils;
import com.kly.user.utils.ServiceUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service("chatterUserService")
public class ChatterUserServiceImpl implements ChatterUserService {
    @Resource
    UserAccountsDao userAccountsDao;

    @Resource
    UserDao userDao;

    @Resource
    UserBehaviorGpsDao userBehaviorGps;

    @Resource
    UserMapper mapper;

    @Resource
    UserAlbumsContentDao userAlbumsContentDao;

    @Resource
    UserAlbumsContentMapper userAlbumsContentMapper;

    @Resource
    UserChatterMappingDao userChatterMappingDao;

    @Resource
    ChatterOptLogDao chatterOptLogDao;

    private static final Integer ZERO = 0;

    private static final Integer ONE = 1;
    @Resource
    UserMessageReportDao userMessageReportDao;
    @Resource
    UserOnlineReportDao userOnlineReportDao;
    @Resource
    UserConversationDao userConversationDao;
    @Resource
    UserMsgForChatterDao userMsgForChatterDao;
    @Resource
    UserConversationNumDao userConversationNumDao;


    // 西五区的时区ID为"UTC-5"
    private static final String timeZoneId = "UTC-8";

    /**
     * chatter登录
     *
     * @param account         账号
     * @param accountPassword 账号密码
     */
    @Override
    public UserInfoDto login(String account, String accountPassword) {
            UserInfoDto userInfoDto = new UserInfoDto();
            Map<String, Object> params = ServiceUtils.getParams();
        params.put("account", account);
//        UserAccountsEntity userAccounts = userAccountsDao.selectByAccount(params);
        List<UserAccountsEntity> userAccounts = userAccountsDao.listByAccount(params);

        if (userAccounts.size() == ZERO) {
            // 5 账号不存在
            userInfoDto.setStatus(5);
            return userInfoDto;
        } else {
            params.put("accountPassword", accountPassword);
            List<UserAccountsEntity> userAccountsEntityList = userAccountsDao.listByAccount(params);
            if (CollUtil.isNotEmpty(userAccountsEntityList) && userAccountsEntityList.size() == ONE) {
                params.clear();
                params.put("userCode", userAccountsEntityList.get(ZERO).getUserCode());
                List<UserEntity> userEntities = userDao.selectByParams(params);
                if (CollUtil.isNotEmpty(userEntities) && userEntities.size() == ONE) {
                    return mapper.UserDtoToUserInfo(userEntities.get(ZERO));
                }
            } else {
                // 6密码错误
                userInfoDto.setStatus(6);
                return userInfoDto;
            }
        }
        return null;
    }

    /**
     * @param userCode 用户码
     * @param type     相册类型
     */
    @Override
    public List<AlbumsResponseDto> getImageUrl(String userCode, Integer type) {
        List<UserAlbumsContentEntity> picturesNumber = userAlbumsContentDao.selectByUserCode(userCode, type);
        if (CollUtil.isNotEmpty(picturesNumber)) {

            return picturesNumber.stream().map(userAlbumsContentMapper::toDto).collect(Collectors.toList());
        } else {
            return null;
        }
    }

    /**
     * 根据用户定位获取对应时区的时间
     *
     * @param userCode 用户码
     */
    @Override
    public Date getDateTime(String userCode) {
//        Map<String, Object> params = ServiceUtils.getParams();
//        params.put("userCode", userCode);
//        List<UserBehaviorGpsEntity> gpsEntities = userBehaviorGps.selectByParams(params);
//        if (CollUtil.isNotEmpty(gpsEntities)) {
//
//        } else {
//
//        }
        String timeZoneId = "UTC-5";
        // 根据时区ID创建ZoneId
        ZoneId zoneId = ZoneId.of(timeZoneId);
        // 使用ZonedDateTime获取当前时区的时间
        ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
        // 将 ZonedDateTime 对象转换为 java.util.Date 对象
        return Date.from(zonedDateTime.toInstant());
    }

    @Override
    public Map<String, UserChatterModeDto> getModeList(String userCode) {
        Map<String, Object> params = ServiceUtils.getParams();
        params.put("chatterUserCode", userCode);
        List<UserChatterMappingEntity> userChatterMappingEntities = userChatterMappingDao.selectByParams(params);
        Map<String, UserChatterModeDto> personMap = new HashMap<>();
        if (CollUtil.isNotEmpty(userChatterMappingEntities)) {
            personMap = userChatterMappingEntities.stream()
                    .map(entity -> {
                        UserChatterModeDto userChatterModeDto = mapper.chatModeToDto(entity);
                        userChatterModeDto.setModelAvatarUrl(ImagePrefixUtils.getFullImageUrl(entity.getModelAvatarUrl()));
                        return userChatterModeDto;
                    })
                    .collect(Collectors.toMap(UserChatterModeDto::getModelUserCode, p -> p));
        }
        return personMap;
    }

    @Override
    public Response storeEventLog(String userCode, String url, Long costTime) {

        ChatterOptLogEntity chatterOptLogEntity = new ChatterOptLogEntity();
        chatterOptLogEntity.setUserCode(userCode);
        chatterOptLogEntity.setUrl(url);
        chatterOptLogEntity.setCostTime(Integer.valueOf(String.valueOf(costTime)));
        chatterOptLogDao.insert(chatterOptLogEntity);
        return Response.ok();

    }

    @Override
    public Response<List<String>> getModelUserCodes(String chatterUserCode) {
        List<String> modelUserCodes = userChatterMappingDao.selectAll(chatterUserCode);
        return Response.ok(modelUserCodes);
    }

    @Override
    public Response<List<UserChatterDto>> getAllChatters() {
        final List<UserChatterMappingEntity> allChatters = userChatterMappingDao.queryAllChatters();
        if (CollectionUtils.isEmpty(allChatters)) {
            return Response.ok();
        }
        final List<UserChatterDto> userChatterDtos = allChatters.parallelStream().map(o -> UserChatterDto.builder().chatterUserCode(o.getChatterUserCode()).chatterAccount(o.getChatterAccount()).chatterNickName(o.getChatterNickName()).build()).collect(Collectors.toList());
        return Response.ok(userChatterDtos);
    }

    @Override
    public Response<UserChatterDto> getChatter(String modelUserCode) {
        if (StringUtils.isEmpty(modelUserCode)) {
            return Response.ok();
        }
        final List<UserChatterMappingEntity> userChatterMappingEntities = userChatterMappingDao.queryByModelUserCodes(Arrays.asList(modelUserCode));
        if (CollectionUtils.isEmpty(userChatterMappingEntities)) {
            return Response.ok();
        }
        final UserChatterMappingEntity chatterEntity = userChatterMappingEntities.get(0);
        final UserChatterDto chatter = UserChatterDto.builder().chatterUserCode(chatterEntity.getChatterUserCode()).chatterAccount(chatterEntity.getChatterAccount()).chatterNickName(chatterEntity.getChatterNickName()).build();
        return Response.ok(chatter);
    }

    @Override
    public Response<ChatterDashboardDto> getChatterDashboardInfo(Integer date, String chatterUserCode) {
        if (StringUtils.isEmpty(chatterUserCode)) {
            return Response.ok();
        }

        final List<UserChatterMappingEntity> userChatterMappingEntities = userChatterMappingDao.queryByChatterUserCode(chatterUserCode);
        if (CollectionUtils.isEmpty(userChatterMappingEntities)) {
            return Response.ok();
        }

        // 获取在线率
        final UserMessageReporDBO userOnlineReportTotal = userOnlineReportDao.getUserOnlineReportTotal(date, chatterUserCode);
        // 获取回复及时率
        final UserMessageReportDBO userMessageReport = userMessageReportDao.getReplyReportTotalByChatterUserCode(date, chatterUserCode);
        // 建联数与承接数
        final UserMessageReportDBO contactAndAcceptance = userMessageReportDao.getContactNum(date, chatterUserCode);

        final int todayDate = Integer.parseInt(DateUtil.format(new Date(), "yyyyMMdd"));

        final UserConversationNumEntity todayConversation = Optional.ofNullable(userConversationNumDao.getUserConversationNumEntity(userChatterMappingEntities.get(0).getChatterUserCode(), todayDate)).orElse(new UserConversationNumEntity());
        
        final ChatterDashboardDto chatterDashboardDto = ChatterDashboardDto.builder().chatterUserCode(chatterUserCode).timelyResponseRate(userMessageReport == null ? 0 : userMessageReport.getReplyOnTimeRageInWorkingTimes2())
                .onlineRate(userOnlineReportTotal == null ? 0 : (userOnlineReportTotal.getOnlineOnWorkingTimesRate() == null ? 0 : userOnlineReportTotal.getOnlineOnWorkingTimesRate())).chats(todayConversation.getAllSessionNum()).newChats(todayConversation.getNewSessionNum())
                .contactNum(contactAndAcceptance == null ? 0 : contactAndAcceptance.getContactNum())
                .acceptanceNum(contactAndAcceptance == null ? 0 : contactAndAcceptance.getAcceptanceNum())
                .acceptanceRate(getRate(contactAndAcceptance)).build();

        return Response.ok(chatterDashboardDto);
    }

    public static Double getRate(UserMessageReportDBO contactAndAcceptance) {
        if (contactAndAcceptance == null || contactAndAcceptance.getAcceptanceNum() == null || contactAndAcceptance.getContactNum() == null) {
            return 0.00;
        }

        BigDecimal a1 = new BigDecimal(contactAndAcceptance.getAcceptanceNum());
        BigDecimal a2 = new BigDecimal(contactAndAcceptance.getContactNum());
        if (a1.compareTo(BigDecimal.ZERO) == 0 || a2.compareTo(BigDecimal.ZERO) == 0) {
            return 0.00;
        }

        NumberFormat nm = new DecimalFormat("#.00");
        final String rate = nm.format(a1.multiply(new BigDecimal("100")).divide(a2, 4, BigDecimal.ROUND_CEILING));
        if (rate.startsWith(".")) {
            return new Double("0" + rate);
        }
        return new Double(rate);
    }



    @Override
    public List<UserChatterModeDto> getModesByModelUserCodes(List<String> modelUserCodes) {

        List<UserChatterMappingEntity> userChatterMappings = userChatterMappingDao.queryByModelUserCodes(modelUserCodes);
        if (CollectionUtils.isEmpty(userChatterMappings)) {
            return null;
        }

        if (CollUtil.isNotEmpty(userChatterMappings)) {
            return userChatterMappings.stream()
                    .map(entity -> {
                        UserChatterModeDto userChatterModeDto = mapper.chatModeToDto(entity);
                        userChatterModeDto.setModelAvatarUrl(ImagePrefixUtils.getFullImageUrl(entity.getModelAvatarUrl()));
                        return userChatterModeDto;
                    }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<UserChatterModeDto> getModesByChatterAccount(String chatterAccount) {
        List<UserChatterMappingEntity> userChatterMappings = userChatterMappingDao.queryByChatterAccount(chatterAccount);
        if (CollUtil.isNotEmpty(userChatterMappings)) {
            return userChatterMappings.stream()
                    .map(entity -> {
                        UserChatterModeDto userChatterModeDto = mapper.chatModeToDto(entity);
                        userChatterModeDto.setModelAvatarUrl(ImagePrefixUtils.getFullImageUrl(entity.getModelAvatarUrl()));
                        return userChatterModeDto;
                    }).collect(Collectors.toList());
        }
        return null;
    }
}
